/*
 * Register.fx
 * Author: Yu Min-ting
 * Created on 2009-7-9, 17:06:54
 */

package com.sjtu.fx.user;

import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.scene.layout.*;
import javafx.scene.shape.Line;
import javafx.ext.swing.*;

import com.sjtu.fx.tools.Panel;
import javafx.scene.control.*;

import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.System;
import org.json.JSONObject;
import org.json.JSONArray;

import java.lang.Math;

import javafx.stage.Alert;

import javafx.geometry.HPos;

import com.sjtu.fx.tools.UIAlert;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;

public class Register extends CustomNode{
    var panel:Panel;
    var category:JSONArray;
    var length:Integer =  category.length();


    public var lname:String = bind lnameTextBox.text;
    public var pw:String = bind pwTextBox.text;
    public var email:String = bind emailTextBox.text;
    public var name:String = bind nameTextBox.text;
    public var dept:String = bind departTextBox.text;
    


    //user login name
    var lnameText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "* Login Name "
    };
    var lnameTextBox = TextBox {
        columns:16
        blocksMouse:false
               
    }

    var lnamePass = ImageView {
            image: Image {
                url: "{__DIR__}pass.png"
            }
            fitWidth: 30
            preserveRatio: true
            cache: true
            smooth: true
            translateX:356 translateY:70
            visible: false
        }
   var lnameFail = ImageView {
            image: Image {
                url: "{__DIR__}fail.png"
            }
            fitWidth: 30
            preserveRatio: true
            smooth: true
            cache: true
            translateX:356 translateY:70
            visible:false
        }


    //user login password
    var pwText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "* Login Password "
    };
    var pwTextBox = TextBox {
        columns:16
        blocksMouse:false
         onMouseEntered: function( e: MouseEvent ):Void {
                userExisted();
        }
    }

    //user email
     var emailText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "* Email-address "
    };
    var emailTextBox = TextBox {
        columns:16
        blocksMouse:false
    }

    //user name
     var nameText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "* Your Name "
    };
    var nameTextBox = TextBox {
        columns:16
        blocksMouse:false
    }

    //user department
     var departText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "Department "
    };
    var departTextBox = SwingComboBox {
            items: [
                SwingComboBoxItem {
                    text: "IDEAS"
                    selected: true
                }
            ]
        }

     //validation code
     var verifyText = Text {
        font: Font {size:10 name: "Verdana"}
        fill: Color.rgb(11,51,60)
        content: "Validation Code "
    };
    var verifyTextBox = TextBox {
        columns:5
        blocksMouse:false
    }
    var verifyLabel = Label {
            text: GenerateCheckCode();
            textFill:Color.ORANGERED
            font:Font {size:16 name: "Verdana Bold"}
        }

    var verifyButton = Hyperlink {
           text: "Regenerate"
            action: function() {
                verifyLabel.text = GenerateCheckCode();
                verifyTextBox.text = "";
            }
    }
           var  cates:Flow =  Flow {
                     id : "cates"
                     translateX:40 translateY:320
                     width: 330
                     height:100
                     hgap: 10 // horizontal gap between nodes in a row
                     vgap: 15 // vertical gap between rows
                     hpos: HPos.LEFT
                     
                }
      var alert = UIAlert {
         translateX:85
         translateY:200
         title:"ERROR"
         content:"Please input entire information"
         width:260
         height:120
         visible:false
         opacity:0.9
     }
     var completeButton = Button {
             text: "Complete"
             translateX:180 translateY:500
             action: function() {
                //not input the full textboxes
                if(lnameTextBox.text==""or pwTextBox.text==""
                     or emailTextBox.text=="" or nameTextBox.text=="")
                {
                    alert.visible = true;
                 // Alert.inform("ERROR","Please input entire information");
                }else{
                      if(verifyTextBox.text!=verifyLabel.text)
                         {
                             alert.content = "Wrong validation code!\n Please input again.";
                             alert.visible = true;
                            //Alert.inform("ERROR","Wrong validation code!\n Please input again.");
                            //regenerate code
                            verifyLabel.text=GenerateCheckCode();
                            verifyTextBox.text = "";
                         }
                         // post request
                         else{

                            sendRegisterInfo();
                            alert.title = "Success";
                            alert.content = "Register Successfully!\n Please login first";
                            alert.visible = true;
                           // Alert.inform("Success","Register Successfully!\n Please login first");
                            visible = false;
                             this.parent.lookup("topBooks").visible = true;
                             this.parent.lookup("recommendBooks").visible = true;
                         }
                 }
            }
    }
     override protected function create() : Node {
        getMainCategory();
        Group{
            content:[
                 panel = Panel {
                    width:    430
                    height:   550
                    title:    "Register"
                    translateX: 0
                    translateY: 0
                },
                //the first part of registration
                Text {
                    x: 40 y: 60
                    font: Font {size:15 name: "Arial Bold"}
                    fill: Color.rgb(11,51,60)
                    content: "1. Enter Your Register Information ( * is required) "
                },
                VBox{
                    spacing: 20
                    translateX:40 translateY: 80
                    content:[lnameText, pwText, emailText]
                },
                 VBox{
                    spacing: 10
                    translateX:180 translateY: 75
                    content:[lnameTextBox, pwTextBox, emailTextBox]
                },
                lnamePass,lnameFail,
                Line {
                    startX: 25
                    startY: 180
                    endX: 405
                    endY: 180
                    stroke:Color.rgb(196,227,227)
                },
                VBox{
                    spacing: 20
                    translateX:40 translateY: 195
                    content:[nameText, departText]
                },
                 VBox{
                    spacing: 10
                    translateX:180 translateY: 190
                    content:[nameTextBox, departTextBox]
                },
                 Line {
                    startX: 25
                    startY: 260
                    endX: 405
                    endY: 260
                    stroke:Color.rgb(196,227,227)
                },

                 //the second part of registration
                Text {
                    x: 40 y: 280
                    font: Font {size:15 name: "Arial Bold"}
                    fill: Color.rgb(11,51,60)
                    content: "2. Choose Your Favourite "
                },
                Text {
                    x: 40 y: 300
                     font: Font {size:10 name: "Verdana"}
                     fill: Color.rgb(11,51,60)
                     content: "We will contact you if we have these kinds of books ingoing! "
                },
                cates,
                Line {
                    startX: 25
                    startY: 420
                    endX: 405
                    endY: 420
                    stroke:Color.rgb(196,227,227)
                },
                 //the third part of registration
                Text {
                    x: 40 y: 445
                    font: Font {size:15 name: "Arial Bold"}
                    fill: Color.rgb(11,51,60)
                    content: "3. Complete Your Registration "
                },
                HBox {
                    spacing: 20
                    translateX:40 translateY: 460
                    content:[verifyText,verifyTextBox,verifyLabel,verifyButton]

                },
                completeButton,alert
            ]
        }
     }

function run() {
    Stage {
       width: 420 height: 520
        scene: Scene {
            content: [
                Register {translateX: 40 translateY: 40}
            ]
        }
    }
}
function getMainCategory(){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/MainCategory"
       onOutput: function(os:OutputStream) {
             try {
                os.write("1".getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                json = new JSONObject(result);
                category = json.getJSONArray("mainCategory");
                var i:Integer = 0;
                length = category.length();
                if(length > 7) length = 7;
                var contents:Node[] ;
                while(i<category.length() and i<=7)
                {
                   var cateBox =  CheckBox {
                             text:  category.get(i).toString()
                             allowTriState: false
                             selected: false
                          }
                    contents[i] = cateBox;
                    i++;
                }
                cates.content = contents;
            } finally {
                is.close();
            }
        }
    }.start();
}
 //generate check code
 function GenerateCheckCode():String
 {
    //initialize
    var ran:Number;
    var number:String;
    var checkCode:String ="";
     //Math.random�
     ran=Math.random();
     number =ran.toString();
     checkCode = number.substring(2, 6);
    return checkCode;
   }
function sendRegisterInfo(){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/Regist"
       onOutput: function(os:OutputStream) {
           System.out.println("Here go");
             try {
                var json:JSONObject = JSONObject{};
                json.put("username",lnameTextBox.text);
                json.put("password",pwTextBox.text);
                json.put("name",nameTextBox.text);
                json.put("email",emailTextBox.text);
                json.put("department",departTextBox.text);
                var i:Integer = 0;
                var catesSelected:String = "";
                System.out.println("length:{length}");
                while(i<length){
                    System.out.println("i:{i}{(cates.content[i] as CheckBox).selected}");
                    if((cates.content[i] as CheckBox).selected){
                        catesSelected += (cates.content[i] as CheckBox).text;
                        catesSelected += "#";
                    }
                    i++;
                }
                json.put("catesSelected",catesSelected );
                var temp:String = "obj={json.toString()}";
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var result:String = data.readLine();
                System.out.println(result);
                Alert.inform(result);
            } finally {
                is.close();
            }
        }
    }.start();
}

function userExisted(){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/UserExisted"
       onOutput: function(os:OutputStream) {
           if(lnameTextBox.text.equals("")){
                
            }else{
           
             try {
                var json:JSONObject = JSONObject{};
                json.put("userName",lnameTextBox.text);
                var temp:String = "obj={json.toString()}";
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var result:String = data.readLine();
                System.out.println(result);
                if(result.equals("true")){
                    lnameFail.visible = true;
                    lnamePass.visible = false;
                    
                }else{
                    lnamePass.visible = true;
                    lnameFail.visible = false;
                    }
                
                
            } finally {
                is.close();
            }
        }
    }.start();
}

}
